// pages/home/home.js
var util = require('../../utils/sever.js');
var network = require('../../utils/network.js');
var timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //车牌选择
    carIdTypeNumbr: "0",
    //车牌输入
    carIdSelectNumbr: 0,
    //车牌类型
    IsNuew: 0,
    //车牌列表
    carIdType: [{
        "typeName": "普通牌"
      },
      {
        "typeName": "新能源牌"
      },
    ],
    //普通
    blueCard: ["", "", "", "", "", "", ""],
    //新能源
    NewCblueCardard: ["", "", "", "", "", "", "", ""],
    //车牌号属地
    CardAdders: ["京", "沪", "粤", "津", "浙", "苏", "湘", "渝",
      "云", "豫", "皖", "陕", "桂", "新", "青", "琼", "闽", "蒙",
      "辽", "鲁", "晋", "吉", "冀", "黑", "台", "甘", "赣", "贵",
      "川", "藏",
    ],
    CardLetter: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
      "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    ],
    CardNumber: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "挂", "学", "警", "港", "澳"],
    carmeal: [],
    carmealtype: 0,
    userIn: {},
    myCarCard: "",
    isShow: "none",
    isGeneralize: "none",
    yzms: 60,
    yzmclic: true,
    yzmnumber: false,
    phone: "",
    authcode: "",
    changeVIP: "立即充值",
    isChangeVIP: false,
    IsKeyShow: true,
    isShow: "none",
    yzmclic: true,
    yzmnumber: false,
    phone: "",
    authcode: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            var pages = getCurrentPages() //获取加载的页面
            var currentPage = pages[pages.length - 1] //获取当前页面的对象
            var urll = currentPage.route + "" //当前页面url
            urll = urll.split("/")
            util.setToken("mypageTow", "../" + urll[1] + "/" + urll[2])
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function() {
      // 新版本下载失败
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    this.CarIdlist()
    this.renelist()
    this.useerInfor()
    this.setData({
      isShow: "none"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //车牌选择
  CarTypeSelect: function(e) {
    var _this = this;
    _this.setData({
      carIdSelectNumbr: 0,
      IsNuew: e.currentTarget.dataset.index,
      blueCard: ["", "", "", "", "", "", ""],
      NewCblueCardard: ["", "", "", "", "", "", "", ""],
      IsKeyShow: true
    })
  },
  //车牌归属地选择
  carIdAdders: function(e) {
    var _this = this;
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    var myNumerUp = _this.data.carIdSelectNumbr
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    myblueCard[0] = _this.data.CardAdders[e.currentTarget.dataset.index]
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp + 1
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp + 1
    })
  },
  //字母选择
  carIdLetter: function(e) {
    var _this = this;
    var myLetter = e.currentTarget.dataset.index
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    var myNumerUp = _this.data.carIdSelectNumbr
    if (myNumerUp >= myblueCard.length) {
      return
    }
    if (myNumerUp < (myblueCard.length - 1)) {
      myNumerUp = myNumerUp + 1
    } else {
      myNumerUp = myNumerUp
    }
    myblueCard[_this.data.carIdSelectNumbr] = _this.data.CardLetter[myLetter]
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp
    })
  },
  //字母选择
  carIdNumber: function(e) {
    var _this = this;
    var myNumber = e.currentTarget.dataset.index
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    var myNumerUp = _this.data.carIdSelectNumbr

    if (myNumerUp >= myblueCard.length) {
      return
    }
    if (myNumerUp < (myblueCard.length - 1)) {
      myNumerUp = myNumerUp + 1
    } else {
      myNumerUp = myNumerUp
    }

    myblueCard[_this.data.carIdSelectNumbr] = _this.data.CardNumber[myNumber]
    // console.log("myNumerUp" + myNumerUp)
    // console.log("myNumerUp" + _this.data.blueCard.length)
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp
    })
  },
  //删除
  backGo: function() {
    var _this = this;
    var myNumber = _this.data.carIdSelectNumbr
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    if (myNumber <= 0) {
      return
    }
    myblueCard[(myNumber)] = ""
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumber - 1
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumber - 1
    })
  },
  //获取套餐
  meal: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/vehicle", "", '正在加载数据', util.myToken("myToken"), function(res) {
        _this.setData({
          carmeal: res.data,
        })
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //支付
  palyBtn: function() {
    var _this = this;
    var myCarId = ''
    var carid = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
    if (_this.data.IsNuew == 0) {
      myCarId = _this.data.blueCard.join('')
    }
    if (_this.data.IsNuew == 1) {
      myCarId = _this.data.NewCblueCardard.join('')
    }
    if (!carid.test(myCarId)) {
      wx.showToast({
        icon: "none",
        title: '请输入正确车牌号',
      })
      return
    }
    console.log(_this.data.IsNuew + " " + myCarId.length)
    if (_this.data.IsNuew == 0 && myCarId.length != 7) {
      wx.showToast({
        icon: "none",
        title: '请输入正确车牌号',
      })
      return
    }
    if (_this.data.IsNuew == 1 && myCarId.length != 8) {
      wx.showToast({
        icon: "none",
        title: '请输入正确车牌号',
      })
      return
    }
    var _this = this;
    var data = {
      vip_recharge_id: _this.data.recharge,
      vehicle_id: myCarId,
    }
    network.requestLoading(util.getRequestUrl + "/api/user/vipPay", data, '正在加载数据', util.myToken("myToken"), function(res) {

        // if (res.msg == "绑定成功") {
        //   wx.showToast({
        //     icon: "none",
        //     title: '绑定成功',
        //   })
        //   setTimeout(function() {
        //     wx.navigateTo({
        //       url: '../caridinfor/caridinfor'
        //     })
        //   }, 2000)

        // } else {
        wx.requestPayment({
          'timeStamp': res.data.timestamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function(res) {
            wx.showToast({
              icon: "none",
              title: '绑定成功',
            })
            setTimeout(function() {

              wx.redirectTo({
                url: '../caridinfor/caridinfor'
              })
            }, 2000)

          },
          'fail': function(res) {
            wx.showToast({
              icon: "none",
              title: '充值失败',
            })
          }
        })
        // }
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //列表
  CarIdlist: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/vehicleList", "", '正在加载数据', util.myToken("myToken"), function(res) {
        // console.log(res.data)
        if (res.data.length != 0) {
          _this.setData({
            carmealtype: 1
          })
        }
        _this.meal()
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //充值套餐
  renelist: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/meal", "", '正在加载数据', util.myToken("myToken"), function(res) {
        var mulist = []
        var muitem = {}
        // console.log(res.data)
        for (var i = 0; i < res.data.length; i++) {
          var car = res.data[i].type_name
          for (var j = 0; j < res.data[i].vip_recharge.length; j++) {
            muitem = res.data[i].vip_recharge[j]
            muitem["carchexing"] = car
            muitem["level"] = res.data[i].level
            mulist.push(muitem)
          }
        }

        _this.setData({
          renList: mulist,
          currentTab: 0,
          recharge: mulist[0].id
        })
        // console.log(_this.data.renList)
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //选择套餐
  selectrene: function(e) {
    var cur = e.currentTarget.dataset.current;
    var recharge = e.currentTarget.dataset.id;
    this.setData({
      currentTab: cur,
      recharge: recharge
    })
  },
  //立即充值
  rechargeup: function() {
    var _this = this;
    // Date.parse(new Date())
    var data = {
      vip_recharge_id: _this.data.recharge
    }
    network.requestLoading(util.getRequestUrl + "/api/user/toVipPay", data, '正在加载数据', util.myToken("myToken"), function(res) {
        wx.requestPayment({
          'timeStamp': res.data.timestamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function(res) {
            _this.useerInfor();
          },
          'fail': function(res) {
            wx.showToast({
              icon: "none",
              title: '充值失败',
            })
          }
        })
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  backNo: function() {
    var _this = this;
    this.setData({
      IsKeyShow: !_this.data.IsKeyShow
    })
  }, //手机号
  phone: function(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  //验证码
  yzmNumber: function(e) {
    this.setData({
      authcode: e.detail.value
    })
  }, //获取验证码
  yzmclick: function() {
    var _this = this;
    var reg = /^[0-9]*$/;
    if (!reg.test(_this.data.phone) || _this.data.phone.length != 11) {
      wx.showToast({
        icon: "none",
        title: '请输入正确手机号',
      })
      return
    }
    wx.showLoading({
      title: '正在获取',
    })
    var data = {
      phone: _this.data.phone
    }
    network.requestLoading(util.getRequestUrl + "/api/user/sendSms", data, '正在加载数据', util.myToken("myToken"), function(res) {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: '获取成功',
        })
        _this.setData({
          yzmclic: false,
          yzmnumber: true,
        })
        _this.countDown()
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  }, //绑定车牌
  upCarCard: function() {
    var _this = this;
    // var carid = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/;
    var carid = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;

    var reg = /^[0-9]*$/;
    if (!reg.test(_this.data.phone) || _this.data.phone.length != 11) {
      wx.showToast({
        icon: "none",
        title: '请输入正确手机号',
      })
      return
    }
    if (!reg.test(_this.data.authcode) || _this.data.authcode.length == 0) {
      wx.showToast({
        icon: "none",
        title: '请输入验证码',
      })
      return
    }
    // if (!carid.test(_this.data.myCarCard)) {
    //   wx.showToast({
    //     icon: "none",
    //     title: '请输入正确车牌号',
    //   })
    //   return
    // }
    var data = {
      // vehicle: _this.data.myCarCard,
      phone: _this.data.phone,
      code: _this.data.authcode
    }
    wx.showLoading({
      title: '正在绑定',
    })
    network.requestLoading(util.getRequestUrl + "/api/user/phoneBound", data, '正在加载数据', util.myToken("myToken"), function(res) {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: '绑定成功',
        })
        _this.setData({
          isShow: "none"
        })
        _this.useerInfor();
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //个人信息
  useerInfor: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/getUserInfo", "", '正在加载数据', util.myToken("myToken"), function(res) {

        if (!res.data.phone) {
          _this.setData({
            isShow: "block"
          })
        }

      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //倒计时
  countDown: function() {
    var _this = this;
    timer = setTimeout(function() {
      _this.setData({
        yzms: --_this.data.yzms,
      })
      if (_this.data.yzms == 0) {
        clearTimeout(timer);
        _this.setData({
          yzmclic: true,
          yzmnumber: false,
          yzms: 60
        })
      } else {
        _this.countDown()
      }

    }, 1000)
  }
})